//
//  JSFPSView.m
//  IJSOCproject
//
//  Created by shange on 2017/5/15.
//  Copyright © 2017年 jinshan. All rights reserved.
//

#import "JSFPSView.h"
#import <CoreText/CoreText.h>


@interface JSFPSView ()
@property (nonatomic, strong) CADisplayLink *displayLink;
/**  属性说明*/
@property (nonatomic, assign) NSInteger scheduleTimes;
/**  属性说明*/
@property (nonatomic, assign) CFTimeInterval timestamp;
/**  属性说明*/
@property (nonatomic, weak) UILabel *label;
@end


@implementation JSFPSView


- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        UILabel *label = [[UILabel alloc] init];
        label.backgroundColor = [UIColor whiteColor];
        //        [self addSubview:label];
        self.label = label;
        [self addDisplayLink];
    }
    return self;
}

- (void)layoutSubviews
{
    self.label.frame = CGRectMake(0, 0, 300, 30);
}

- (void)addDisplayLink
{
    //创建CADisplayLink，并添加到当前run loop的NSRunLoopCommonModes
    _displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(linkTicks:)];
    [_displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
}

- (void)linkTicks:(CADisplayLink *)link
{
    //执行次数
    _scheduleTimes++;

    //当前时间戳
    if (_timestamp == 0) {
        _timestamp = link.timestamp;
    }
    CFTimeInterval timePassed = link.timestamp - _timestamp;

    if (timePassed >= 1.f) {
        //fps
        CGFloat fps = _scheduleTimes / timePassed;
        printf("fps:%.1f, timePassed:%f\n", fps, timePassed);
        //        self.label.text = [NSString stringWithFormat:@"fps:%.1f, timePassed:%f\n", fps, timePassed];
        //reset
        _timestamp = link.timestamp;
        _scheduleTimes = 0;
    }
}


/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
